// 菜单管理系统 - 统一管理房间菜单和模板

// 存储键名常量
const STORAGE_KEYS = {
  ROOM_MENUS: 'roomMenus',           // 房间菜单配置
  MENU_TEMPLATES: 'menuTemplates',   // 菜单模板
  USER_FAVORITES: 'userFavorites',   // 用户收藏
  DEFAULT_MENU: 'defaultMenu'        // 默认菜单
};

// 菜单来源类型
const MENU_SOURCES = {
  TEMPLATE: 'template',      // 模板菜单
  CUSTOM: 'custom',          // 自定义菜单
  IMPORTED: 'imported',      // 导入菜单
  DEFAULT: 'default'         // 默认菜单
};

// 默认菜单模板
const DEFAULT_MENU_TEMPLATE = {
  templateId: 'default',
  name: '默认菜单',
  description: '经典菜品模板，适合大多数聚餐场景',
  menuItems: [
    // 热菜类
    {
      id: 1,
      name: '宫保鸡丁',
      image: 'https://img.yzcdn.cn/vant/cat.jpeg',
      tags: ['微辣', '热菜', '川菜'],
      category: 'hot',
      flavors: ['不辣', '微辣', '中辣', '特辣'],
      count: 0
    },
    {
      id: 2,
      name: '麻婆豆腐',
      image: 'https://img.yzcdn.cn/vant/cat.jpeg',
      tags: ['中辣', '热菜', '川菜'],
      category: 'hot',
      flavors: ['不辣', '微辣', '中辣', '特辣'],
      count: 0
    },
    {
      id: 3,
      name: '糖醋里脊',
      image: 'https://img.yzcdn.cn/vant/cat.jpeg',
      tags: ['酸甜', '热菜', '鲁菜'],
      category: 'hot',
      flavors: ['酸甜', '糖醋'],
      count: 0
    },
    {
      id: 4,
      name: '红烧肉',
      image: 'https://img.yzcdn.cn/vant/cat.jpeg',
      tags: ['咸香', '热菜', '家常'],
      category: 'hot',
      flavors: ['咸香', '微甜'],
      count: 0
    },
    {
      id: 5,
      name: '鱼香肉丝',
      image: 'https://img.yzcdn.cn/vant/cat.jpeg',
      tags: ['微辣', '热菜', '川菜'],
      category: 'hot',
      flavors: ['不辣', '微辣', '中辣'],
      count: 0
    },
    // 凉菜类
    {
      id: 6,
      name: '凉拌黄瓜',
      image: 'https://img.yzcdn.cn/vant/cat.jpeg',
      tags: ['清爽', '凉菜', '素食'],
      category: 'cold',
      flavors: ['清淡', '微酸'],
      count: 0
    },
    {
      id: 7,
      name: '口水鸡',
      image: 'https://img.yzcdn.cn/vant/cat.jpeg',
      tags: ['麻辣', '凉菜', '川菜'],
      category: 'cold',
      flavors: ['微辣', '中辣', '特辣'],
      count: 0
    },
    // 主食类
    {
      id: 8,
      name: '米饭',
      image: 'https://img.yzcdn.cn/vant/cat.jpeg',
      tags: ['主食', '米饭'],
      category: 'staple',
      flavors: ['白米饭', '糙米饭'],
      count: 0
    },
    {
      id: 9,
      name: '面条',
      image: 'https://img.yzcdn.cn/vant/cat.jpeg',
      tags: ['主食', '面条'],
      category: 'staple',
      flavors: ['汤面', '拌面'],
      count: 0
    },
    // 汤类
    {
      id: 10,
      name: '西红柿鸡蛋汤',
      image: 'https://img.yzcdn.cn/vant/cat.jpeg',
      tags: ['清淡', '汤类', '家常'],
      category: 'soup',
      flavors: ['清淡', '微酸'],
      count: 0
    },
    // 饮料类
    {
      id: 11,
      name: '可乐',
      image: 'https://img.yzcdn.cn/vant/cat.jpeg',
      tags: ['饮料', '碳酸'],
      category: 'drink',
      flavors: ['冰镇', '常温'],
      count: 0
    },
    {
      id: 12,
      name: '橙汁',
      image: 'https://img.yzcdn.cn/vant/cat.jpeg',
      tags: ['饮料', '果汁'],
      category: 'drink',
      flavors: ['冰镇', '常温'],
      count: 0
    }
  ],
  isDefault: true,
  createdAt: Date.now()
};

// 菜单管理器类
class MenuManager {
  constructor() {
    this.initDefaultData();
  }

  // 初始化默认数据
  initDefaultData() {
    // 初始化默认菜单模板
    const templates = wx.getStorageSync(STORAGE_KEYS.MENU_TEMPLATES) || {};
    if (!templates['default']) {
      templates['default'] = DEFAULT_MENU_TEMPLATE;
      wx.setStorageSync(STORAGE_KEYS.MENU_TEMPLATES, templates);
    }

    // 初始化默认菜单
    if (!wx.getStorageSync(STORAGE_KEYS.DEFAULT_MENU)) {
      wx.setStorageSync(STORAGE_KEYS.DEFAULT_MENU, DEFAULT_MENU_TEMPLATE.menuItems);
    }
  }

  // 获取房间菜单配置
  getRoomMenuConfig(roomId) {
    const roomMenus = wx.getStorageSync(STORAGE_KEYS.ROOM_MENUS) || {};
    return roomMenus[roomId] || this.createDefaultRoomMenuConfig(roomId);
  }

  // 创建默认房间菜单配置
  createDefaultRoomMenuConfig(roomId) {
    const defaultConfig = {
      roomId: roomId,
      menuSource: MENU_SOURCES.TEMPLATE,
      templateId: 'default',
      customMenuItems: [],
      allowUserFavorites: true,
      allowParticipantAdd: false,
      lastUpdated: Date.now()
    };

    this.saveRoomMenuConfig(roomId, defaultConfig);
    return defaultConfig;
  }

  // 保存房间菜单配置
  saveRoomMenuConfig(roomId, config) {
    const roomMenus = wx.getStorageSync(STORAGE_KEYS.ROOM_MENUS) || {};
    roomMenus[roomId] = {
      ...config,
      roomId: roomId,
      lastUpdated: Date.now()
    };
    wx.setStorageSync(STORAGE_KEYS.ROOM_MENUS, roomMenus);
  }

  // 加载房间菜单
  loadRoomMenu(roomId) {
    const config = this.getRoomMenuConfig(roomId);
    let menuItems = [];

    switch (config.menuSource) {
      case MENU_SOURCES.DEFAULT:
        menuItems = this.loadDefaultMenu();
        break;
      case MENU_SOURCES.TEMPLATE:
        menuItems = this.loadTemplateMenu(config.templateId);
        break;
      case MENU_SOURCES.CUSTOM:
        menuItems = config.customMenuItems || [];
        break;
      case MENU_SOURCES.IMPORTED:
        menuItems = this.loadImportedMenu(config.importedFrom);
        break;
      default:
        menuItems = this.loadDefaultMenu();
    }

    // 如果允许用户收藏，合并收藏菜品
    if (config.allowUserFavorites) {
      menuItems = this.mergeUserFavorites(menuItems);
    }

    return menuItems;
  }

  // 加载模板菜单
  loadTemplateMenu(templateId) {
    const templates = wx.getStorageSync(STORAGE_KEYS.MENU_TEMPLATES) || {};
    const template = templates[templateId];
    return template ? template.menuItems : this.loadDefaultMenu();
  }

  // 加载默认菜单
  loadDefaultMenu() {
    return wx.getStorageSync(STORAGE_KEYS.DEFAULT_MENU) || DEFAULT_MENU_TEMPLATE.menuItems;
  }

  // 加载导入菜单
  loadImportedMenu(importedFrom) {
    // 从其他房间导入菜单
    if (importedFrom && importedFrom.startsWith('room_')) {
      return this.loadRoomMenu(importedFrom);
    }
    // 从模板导入菜单
    if (importedFrom && importedFrom.startsWith('template_')) {
      return this.loadTemplateMenu(importedFrom.replace('template_', ''));
    }
    return this.loadDefaultMenu();
  }

  // 合并用户收藏
  mergeUserFavorites(menuItems) {
    const favorites = wx.getStorageSync(STORAGE_KEYS.USER_FAVORITES) || [];
    const favoriteItems = favorites.map(favId => this.getMenuItemById(favId)).filter(Boolean);
    
    // 合并并去重
    const existingIds = new Set(menuItems.map(item => item.id));
    const newFavorites = favoriteItems.filter(item => !existingIds.has(item.id));
    
    return [...menuItems, ...newFavorites];
  }

  // 根据ID获取菜品
  getMenuItemById(itemId) {
    const defaultMenu = wx.getStorageSync(STORAGE_KEYS.DEFAULT_MENU) || [];
    return defaultMenu.find(item => item.id === itemId);
  }

  // 添加菜品到房间菜单
  addMenuItemToRoom(roomId, menuItem) {
    const config = this.getRoomMenuConfig(roomId);
    
    if (config.menuSource === MENU_SOURCES.CUSTOM) {
      // 自定义菜单模式，直接添加
      config.customMenuItems = config.customMenuItems || [];
      config.customMenuItems.push(menuItem);
    } else {
      // 其他模式，切换到自定义模式
      config.menuSource = MENU_SOURCES.CUSTOM;
      config.customMenuItems = this.loadRoomMenu(roomId);
      config.customMenuItems.push(menuItem);
    }
    
    this.saveRoomMenuConfig(roomId, config);
  }

  // 从房间菜单删除菜品
  removeMenuItemFromRoom(roomId, itemId) {
    const config = this.getRoomMenuConfig(roomId);
    
    if (config.menuSource === MENU_SOURCES.CUSTOM) {
      config.customMenuItems = (config.customMenuItems || []).filter(item => item.id !== itemId);
      this.saveRoomMenuConfig(roomId, config);
    }
  }

  // 保存菜单为模板
  saveMenuAsTemplate(roomId, templateName, description = '') {
    const menuItems = this.loadRoomMenu(roomId);
    const templateId = `template_${Date.now()}`;
    
    const template = {
      templateId: templateId,
      name: templateName,
      description: description,
      menuItems: menuItems,
      isDefault: false,
      createdAt: Date.now()
    };
    
    const templates = wx.getStorageSync(STORAGE_KEYS.MENU_TEMPLATES) || {};
    templates[templateId] = template;
    wx.setStorageSync(STORAGE_KEYS.MENU_TEMPLATES, templates);
    
    return templateId;
  }

  // 获取所有菜单模板
  getAllTemplates() {
    const templates = wx.getStorageSync(STORAGE_KEYS.MENU_TEMPLATES) || {};
    return Object.values(templates).sort((a, b) => a.createdAt - b.createdAt);
  }

  // 设置房间菜单来源
  setRoomMenuSource(roomId, source, sourceId = null) {
    const config = this.getRoomMenuConfig(roomId);
    config.menuSource = source;
    
    switch (source) {
      case MENU_SOURCES.DEFAULT:
        config.templateId = 'default';
        break;
      case MENU_SOURCES.TEMPLATE:
        config.templateId = sourceId || 'default';
        break;
      case MENU_SOURCES.IMPORTED:
        config.importedFrom = sourceId;
        break;
      case MENU_SOURCES.CUSTOM:
        // 保持现有自定义菜品
        break;
    }
    
    this.saveRoomMenuConfig(roomId, config);
  }

  // 迁移现有房间数据
  migrateExistingRooms() {
    const rooms = wx.getStorageSync('rooms') || [];
    const roomMenus = wx.getStorageSync(STORAGE_KEYS.ROOM_MENUS) || {};
    
    rooms.forEach(room => {
      if (!roomMenus[room.roomId]) {
        roomMenus[room.roomId] = {
          roomId: room.roomId,
          menuSource: MENU_SOURCES.TEMPLATE,
          templateId: 'default',
          customMenuItems: [],
          allowUserFavorites: true,
          allowParticipantAdd: false,
          lastUpdated: Date.now()
        };
      }
    });
    
    wx.setStorageSync(STORAGE_KEYS.ROOM_MENUS, roomMenus);
  }
}

// 创建全局实例
const menuManager = new MenuManager();

// 导出
module.exports = {
  menuManager,
  STORAGE_KEYS,
  MENU_SOURCES
};
